import { api } from "@/api/user";
import { getToken, removeToken, setToken } from "@/utils/auth";
import { Utils } from "@/utils/Util";
import { Message } from "element-ui";

const state = {
    token: getToken() || "",
    name: "",
    roles: ""
};

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token;
    },
    SET_NAME: (state, name) => {
        state.name = name;
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles;
    }
};

const actions = {
    login({ commit }, userInfo) {
        const { username, password } = userInfo;
        return new Promise((resolve, reject) => {
            api
              .login({ username: username, password: password })
              .then((response) => {
                  const data = response.data;
                  console.log("登录返回信息::", response);
                  if (response.code !== 200) {
                      Message.error(response.data);
                      resolve();
                      return;
                  }
                  Utils.putLocalStorage("userInfo", response.data);
                  commit("SET_TOKEN", data);
                  setToken(data);
                  resolve();
              })
              .catch((err) => {
                  reject(err);
              });
        });
    },
    
    logout({ commit }) {
        return new Promise((resolve) => {
            removeToken();
            commit("SET_TOKEN", "");
            commit("SET_ROLES", "");
            localStorage.clear();
            resolve();
        });
    },
    
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            api
              .getInfo(state.token)
              .then((response) => {
                  
                  console.log("用户信息请求::", response);
                  if (!response) {
                      return reject("Verification failed, please Login again.");
                  }
                  const { username, role } = response;
                  commit("SET_NAME", username);
                  commit("SET_ROLES", role);
                  resolve(response);
              })
              .catch((error) => {
                  reject(error);
              });
        });
    },
    
    changeInfo({ state }, userInfo) {
        const username = state.name;
        const { pass, checkPass } = userInfo;
        console.log(username, pass, checkPass);
        return new Promise((resolve, reject) => {
            api
              .changeInfo({
                  username: username,
                  oldPassword: pass,
                  newPassword: checkPass
              })
              .then((res) => {
                  console.log(res.data);
                  resolve();
              })
              .catch((err) => {
                  reject(err);
              });
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
